package auth

import (
	"GraduationProject/public/db"
	"GraduationProject/public/models"
	"GraduationProject/webserver/controllers/util"
	"GraduationProject/webserver/status"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
)

func Register(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	passwordCheck := c.PostForm("password_check")
	nickname := c.PostForm("nickname")
	phone := c.PostForm("phone")
	//avatar := c.PostForm("avatar")
	if username == "" || password == "" || nickname == "" {
		util.FailedResponse(c, 10001, "参数不能为空")
		return
	}

	if password != passwordCheck {
		util.FailedResponse(c, status.PasswordIsDifferent, "两次密码不一致")
		return
	}

	var user models.User
	if err := db.DB.Where("`username` = ?", username).
		First(&user).Error; err == nil {
		util.FailedResponse(c, status.UsernameExist, "用户名已存在")
		return
	} else if err == gorm.ErrRecordNotFound {
		if err := db.DB.Create(&models.User{
			Username:      username,
			Password:      util.Sha256(password),
			Authorization: models.UserAuthNormal,
			Nickname:      nickname,
			Phone:         phone,
			//Avatar:        avatar,
			Status: models.UserStatusRegister,
		}).Error; err != nil {
			util.FailedResponse(c, 10002, "注册失败")
			return
		}
		util.SuccessResponse(c)
		return
	}
	util.FailedResponse(c, 10003, "未知错误")
	return

}
